﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EnterpriseManagement.Models;
using Webdiyer.WebControls.Mvc;

namespace EnterpriseManagement.Controllers
{
    public class ProjectController : Controller
    {
        /// <summary>
        /// 查询员工相关项目信息(普通员工)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult EmployeeProject()    //若传入id不合法？
        {
            string userName = HttpContext.User.Identity.Name;
            List<ProjectDetailsModel> list = FormsService.GetProjectDetail(userName);
            if (list == null)                   //不存在相应的项目信息
            {
                ModelState.AddModelError(string.Empty, "没有相关项目信息");
                return View("ErrorPage");
            }
            else
            {
                return PartialView(list);
            }
        }

        [AuthorizeGroup(Group = "Super")]
        public ActionResult CreateClient()
        {
            return PartialView();
        }

        [AuthorizeGroup(Group = "Super")]
        [HttpPost]
        public ActionResult CreateClient(CreateClientModel model)
        {
            if (ModelState.IsValid)
            {
                if (FormsService.CreateClient(model) == ExecuteResult.Success)
                {
                    ModelState.AddModelError(string.Empty, "新建成功");
                    return PartialView(model);
                }
                ModelState.AddModelError(string.Empty, "新建成功");
                return PartialView(model);
            }
            return PartialView(model);
        }

        [AuthorizeGroup(Group="Super")]
        public ActionResult ProjectMemberDistribute()
        {
           return PartialView ( FormsService.GetProjectEmployeePositionDistribute());
        }

        [AuthorizeGroup(Group="Super")]
        public ActionResult AddTeammember()
        {
            List<string> projectName = FormsService.GetAllProjectNames();
            SelectList projectNameList = new SelectList(projectName);
            ViewData["ProjectName"] = projectNameList;

            List<string> position=FormsService.GetAllPositions();
            SelectList positionList = new SelectList(position);
            ViewData["Position"] = positionList;
            return PartialView();
          
        }

        [HttpPost]
        [AuthorizeGroup(Group = "Super")]
        public ActionResult AddTeammember(TeamMemberModel model)
        {
            List<string> projectName = FormsService.GetAllProjectNames();
            SelectList projectNameList = new SelectList(projectName);
            ViewData["ProjectName"] = projectNameList;

            List<string> position = FormsService.GetAllPositions();
            SelectList positionList = new SelectList(position);
            ViewData["Position"] = positionList;

            if (ModelState.IsValid)
            {
                if (FormsService.AddTeammember(model.ProjectName, model.EmployeeId, model.Position, null, model.DirectorId) == ExecuteResult.Success)
                {
                    ModelState.AddModelError(string.Empty, "添加成功");
                    return PartialView();
                }
            }
            return PartialView();
        }

        //可以通过判断是否为AJAX请求来防盗链
        /// <summary>
        /// 获取项目组员工信息的PartialView
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult TeamMember(string projectName,string id)
        {
            //string projectName = id;
            if (Request.IsAjaxRequest() && projectName != null)
            {
                List<TeamMemberModel> list = FormsService.GetTeamMembers(projectName);
                if (list == null)
                {
                    ViewData["ErrorMessage"] = ErrorHandling.ErrorCodeToString(ExecuteResult.NoTeamMemberInformation);
                    return PartialView("ErrorPage");
                }
                else
                {
                    int currentPage;
                    int.TryParse(id, out currentPage);
                    if (currentPage <= 0 || currentPage > list.Count() / 8 + (list.Count() % 8 == 0 ? 0 : 1))
                        currentPage = 1;
                    PagedList<TeamMemberModel> pageList = new PagedList<TeamMemberModel>(list, currentPage, 8);

                    if (FormsService.IsSuper(HttpContext.User.Identity.Name))
                    {
                        return PartialView("TeamMember", pageList);
                    }
                    return PartialView("NormalTeammember", pageList);
                }
            }
            else
            {
                ViewData["ErrorMessage"] = ErrorHandling.ErrorCodeToString(ExecuteResult.NoTeamMemberInformation);
                return PartialView("ErrorPage");
            }
        }

        [AuthorizeGroup(Group = "Super")]
        public ActionResult EditTeammember(string id)
        {
            string projectName;
            string employeeId;
            string[] temp = id.Split(',');                   //temp[0]:projectName,temp[1]:employeeId
            //若传入数据格式有误则返回项目首页
            if (temp.Count() != 2)
            {
                ViewData["ErrorMessage"] = ErrorHandling.ErrorCodeToString(ExecuteResult.NoTeamMemberInformation);
                return PartialView("ErrorPage");
            }
            else
            {
                projectName = temp[0];
                employeeId = temp[1];
            }

            TeamMemberModel model = DbHelper.GetTeamMember(projectName, employeeId);
            if (model == null)
            {
                ViewData["ErrorMessage"] = ErrorHandling.ErrorCodeToString(ExecuteResult.NoTeamMemberInformation);
                return PartialView("ErrorPage");
            }

            List<string> position = FormsService.GetAllPositions();
            SelectList positionList = new SelectList(position);
            ViewData["Position"] = positionList;

            return PartialView(model);
        }

        [AuthorizeGroup(Group = "Super")]
        [HttpPost]
        public ActionResult EditTeammember(TeamMemberModel model)
        {
            if (ModelState.IsValid)
            {
                if (FormsService.UpdateTeammember(model) == ExecuteResult.Success)
                {
                    List<string> position = FormsService.GetAllPositions();
                    SelectList positionList = new SelectList(position);
                    ViewData["Position"] = positionList;

                    ModelState.AddModelError(string.Empty, "更新成功");
                    return PartialView("EditTeammember");
                }
                ModelState.AddModelError(string.Empty, "输入信息有误，请检查后重新操作");
                return PartialView("ErrorPage");
            }
            ModelState.AddModelError(string.Empty, "输入信息有误，请检查后重新操作");
            return PartialView("ErrorPage");
        }

        /// <summary>
        /// 直接释放项目组成员，不添加到新的项目组（默认为FreeBuffer）
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ReleaseTeammember(string id)
        {
            if (Request.IsAjaxRequest())
            {
                string projectName;
                string employeeId;
                string[] temp = id.Split(',');                   //temp[0]:projectName,temp[1]:employeeId
                if (temp.Count() != 2)
                {
                    ViewData["ErrorMessage"] = "Error";
                    return PartialView("ErrorPage");
                }
                else
                {
                    projectName = temp[0];
                    employeeId = temp[1];
                }

                if (FormsService.DispatchTeammember(employeeId, projectName) == ExecuteResult.Success)
                {
                    ModelState.AddModelError(string.Empty, "释放成功");
                    return PartialView("ErrorPage");
                }
                ModelState.AddModelError(string.Empty, "释放到FreeBuffer失败");
                return PartialView("ErrorPage");
                
            }
            else
            {
                ModelState.AddModelError(string.Empty, "你没有此权限");
                return PartialView("ErrorPage");
            }
        }

        public ActionResult ReleaseTeammemberToNewProject(string id)
        {
            if (Request.IsAjaxRequest())
            {
                string projectName;
                string employeeId;
                string[] temp = id.Split(',');                   //temp[0]:projectName,temp[1]:employeeId
                if (temp.Count() != 2)
                {
                    ViewData["ErrorMessage"] = "Error";
                    return PartialView("ErrorPage");
                }
                else
                {
                    projectName = temp[0];
                    employeeId = temp[1];
                }

                TeamMemberModel model = new TeamMemberModel();
                model.oldProjectName = projectName;
                model.EmployeeId = employeeId;
                model.EmployeeName = FormsService.GetEmployeeById(employeeId).name;

                List<string> projectname = FormsService.GetAllProjectNames();
                projectname.Remove(model.oldProjectName);
                SelectList projectnameList = new SelectList(projectname);
                ViewData["ProjectName"] = projectnameList;

                List<string> position = FormsService.GetAllPositions();
                SelectList positionList = new SelectList(position);
                ViewData["Position"] = positionList;
                //其他值默认是Null，可能会出错
                return PartialView(model);
            }
            else
            {
                ModelState.AddModelError(string.Empty, "你没有此权限");
                return PartialView("ErrorPage");
            }
        }

        [HttpPost]
        public ActionResult ReleaseTeammemberToNewProject(TeamMemberModel model)
        {
            if (Request.IsAjaxRequest())
            {
                List<string> projectname = FormsService.GetAllProjectNames();
                projectname.Remove(model.oldProjectName);
                SelectList projectnameList = new SelectList(projectname);
                ViewData["ProjectName"] = projectnameList;

                List<string> position = FormsService.GetAllPositions();
                SelectList positionList = new SelectList(position);
                ViewData["Position"] = positionList;

                if (ModelState.IsValid)
                {
                    if (FormsService.DispatchTeammember(model.EmployeeId, model.oldProjectName, model.ProjectName, model.Position, model.DirectorId) == ExecuteResult.Success)
                    {
                        ModelState.AddModelError(string.Empty, "更改成功");
                        return PartialView();
                    }
                    ModelState.AddModelError(string.Empty, "填写的信息有误，请检查后重试");
                    return PartialView();
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "填写的信息有误，请检查后重试");
                    return PartialView();
                }
            }
            else
            {
                ModelState.AddModelError(string.Empty, "你没有此权限");
                return PartialView("ErrorPage");
            }
        }


        [AuthorizeGroup(Group="Super")]
        public ActionResult CreateProject()
        {
            return PartialView();
        }

        [HttpPost]
        [AuthorizeGroup(Group = "Super")]
        public ActionResult CreateProject(CreateProjectModel model)
        {
            if (ModelState.IsValid)
            {
                if (FormsService.CreateProject (model.ProjectName ,model .ManagerId ,model.StartTime )==ExecuteResult.Success)
                {
                    //add teammeber
                    
                    ModelState.AddModelError(string.Empty, "创建成功");
                    return PartialView(model);
                }

                ModelState.AddModelError(string.Empty, "项目名称重复或项目经理ID不存在");
            }
            return PartialView();
        }

        [AuthorizeGroup (Group=("Super"))]
        public ActionResult DeleteProject()
        {
            return PartialView();
        }

        [HttpPost]
        [AuthorizeGroup(Group = ("Super"))]
        public ActionResult DeleteProject(DeleteProjectModel model)
        {
            if (ModelState.IsValid)
            {
                if (FormsService.DeleteProject(model.ProjectName,model.SuperPassword) == ExecuteResult.Success)
                {
                    ModelState.AddModelError(string.Empty, "删除成功");
                    return PartialView(model);
                }

                ModelState.AddModelError(string.Empty, "项目组不存在或项目组中还有员工，请确认后再操作");
            }
            return PartialView();
        }

        [AuthorizeGroup (Group="Super")]
        public ActionResult SearchProject()
        {
            List<string> list = FormsService.GetAllProjectStatus();
            SelectList ProjectStatus = new SelectList(list);
            ViewData["ProjectStatus"] = ProjectStatus;

            List<string> list2 = FormsService.GetAllProjectNames();
            SelectList ProjectName = new SelectList(list2);
            ViewData["ProjectName"] = ProjectName;

            List<string> list3 = FormsService.GetAllClient();
            SelectList ClientName = new SelectList(list3);
            ViewData["ClientName"] = ClientName;

            return PartialView();
        }

        [AuthorizeGroup(Group = "Super")]
        [HttpPost]
        public ActionResult SearchProject(SearchProjectModel model,string id)
        {
            if (ModelState.IsValid)
            {
                List<ProjectDetailsModel> projectList = FormsService.SearchProject(model);
                if (projectList.Count() != 0)
                {
                    int currentPage;
                    int.TryParse(id, out currentPage);
                    if (currentPage <= 0 || currentPage > projectList.Count() / 8 + (projectList.Count() % 8 == 0 ? 0 : 1))
                        currentPage = 1;
                    PagedList<ProjectDetailsModel> pageList = new PagedList<ProjectDetailsModel>(projectList, currentPage, 8);
                    return PartialView("ProjectDetail", pageList);
                }
            }
            ModelState.AddModelError(string.Empty, "无相关项目信息");
            return PartialView("ErrorPage");
        }

        [AuthorizeGroup (Group="Super")]
        public ActionResult EditProject(string  id)
        {
            string projectName = id;
            //没有相应的project存在则为Null
            ProjectDetailsModel model = FormsService.GetProjectByProjectName(projectName);
            if (model == null)
            {
                ViewData ["ErrorMessage"]="无法访问";
                return PartialView("ErrorPage");
            }
            List<string> list = new List<string>();
            list.Add("Cancelled");
            list.Add("On Progress");
            list.Add("Pending");
            list.Add("Completed");
            SelectList ProjectStatus = new SelectList(list);
            ViewData["ProjectStatus"] = ProjectStatus;

            List<string> list2 = FormsService.GetAllClient();
            SelectList ClientName = new SelectList(list2);
            ViewData["ClientName"] = ClientName;

            return PartialView(model);
        }

        [AuthorizeGroup(Group = "Super")]
        [HttpPost]
        public ActionResult UpdateProject(ProjectDetailsModel model)
        {
            List<string> list = new List<string>();
            list.Add("Cancelled");
            list.Add("On Progress");
            list.Add("Pending");
            list.Add("Completed");
            SelectList ProjectStatus = new SelectList(list);
            ViewData["ProjectStatus"] = ProjectStatus;

            List<string> list2 = FormsService.GetAllClient();
            SelectList ClientName = new SelectList(list2);
            ViewData["ClientName"] = ClientName;
            if (ModelState.IsValid)
            {
                if (FormsService.UpdateProject(model) == ExecuteResult.Success)
                {
                    ModelState.AddModelError(string.Empty, "更新成功");
                    return PartialView("EditProject",model);
                }
                ModelState.AddModelError(string.Empty, "输入信息有误，请检查后重新操作");
                return PartialView("EditProject", model);
            }
            ModelState.AddModelError(string.Empty, "输入信息有误，请检查后重新操作");
            return PartialView("EditProject", model);
        }
     
    }
}
